package dj.service.impl;

import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import dj.Constant;
import dj.dao.BaseDao;
import dj.model.SmsStatus;
import dj.service.SmsService;
import dj.utils.StringUtils;
import dj.webservice.mas.org.csapi.schema.sms.DeliveryInformation;
import dj.webservice.mas.org.csapi.schema.sms.MessageFormat;
import dj.webservice.mas.org.csapi.schema.sms.NotifySmsDeliveryStatusRequest;
import dj.webservice.mas.org.csapi.schema.sms.SendMethodType;
import dj.webservice.mas.org.csapi.schema.sms.SendSmsRequest;
import dj.webservice.mas.org.csapi.schema.sms.SendSmsResponse;

@Service("smsService")
public class SmsServiceImpl implements SmsService {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(SmsServiceImpl.class);

	private BaseDao<SmsStatus> smsDao;

	public BaseDao<SmsStatus> getSmsDao() {
		return smsDao;
	}

	@Autowired
	public void setSmsDao(BaseDao<SmsStatus> smsDao) {
		this.smsDao = smsDao;
	}

	public void save(SmsStatus ss) {
		smsDao.save(ss);
	}

	public String sendSms(List<String> phones, String message, String companyid, String reportid) {
		String requestIdentifier = "";
		String status = "";
		if (null != phones && phones.size() > 0) {
			String extendCode = "";
			try {
				extendCode = StringUtils.getSeralNum("sms.serial");
				SendSmsRequest ssr = new SendSmsRequest();
				ssr.setApplicationID(Constant.APPLICATIONID);
				ssr.setDeliveryResultRequest(true);
				ssr.setExtendCode(extendCode);
				ssr.setMessage(message);
				ssr.setMessageFormat(MessageFormat.UCS_2);
				ssr.setSendMethod(SendMethodType.LONG);
				for (String phone : phones) {
					ssr.getDestinationAddresses().add("tel:" + phone);
				}

				try {
					// 发送短信
					SendSmsResponse ssre = Constant.smws.sendSms(ssr);
					requestIdentifier = ssre.getRequestIdentifier();
					status = "短信已发送";
				} catch (Exception e) {
					status = "短信发送失败，" + e.getMessage();
					logger.error(e.getMessage());
					e.printStackTrace();
				}
			} catch (Exception e1) {
				status = "短信发送失败，获取扩展号码失败！";
				logger.error(e1.getMessage());
				e1.printStackTrace();
			}

			for (String phone : phones) {
				SmsStatus ss = new SmsStatus();
				ss.setId(UUID.randomUUID().toString());
				ss.setApplicationid(Constant.APPLICATIONID);
				ss.setPhone(phone);
				ss.setMessage(message);
				ss.setRequestidentifier(requestIdentifier);
				ss.setSendTime(new Timestamp(new Date().getTime()));
				ss.setType("send");
				ss.setCompanyid(companyid);
				ss.setReportid(reportid);
				ss.setReplyCode(status);
				ss.setSystemNum(extendCode);

				save(ss);
			}
		}

		return status;
	}

	public void updateSmsStatus(NotifySmsDeliveryStatusRequest parameter) {

		String hql = "update SmsStatus set replyCode=:replyCode where requestidentifier=:requestidentifier and phone=:phone";

		if (null != parameter.getDeliveryInformation() && parameter.getDeliveryInformation().size() > 0) {
			for (DeliveryInformation di : parameter.getDeliveryInformation()) {
				if (null != di.getAddress() && di.getAddress().length() >= 15) {
					Map<String, Object> params = new HashMap<String, Object>();
					params.put("replyCode", di.getDeliveryStatus().value());
					params.put("requestidentifier", parameter.getRequestIdentifier());
					params.put("phone", di.getAddress().substring(4));

					smsDao.executeHql(hql, params);
				}
			}
		}
	}

}
